﻿namespace Admin.NET.Application.Job;

/// <summary>
/// 再次请求AGV出库暂存任务
/// </summary>
[JobDetail("Job_AgvOutBoundTaskJob", Description = "再次请求AGV出库暂存任务", GroupName = "AGVTask", Concurrent = false)]
//[Daily(TriggerId = "trigger_repeatAgvOutBoundTaskJob", Description = "再次请求AGV出库暂存任务")]
[PeriodMinutes(1, TriggerId = "trigger_AgvOutBoundTaskJob", StartNow = true, RunOnStart = true)]

public class AddAgvStagingOutBoundTask : IJob
{
    #region 关系注入
    private readonly TaskService taskService = new TaskService();
    private readonly BaseService baseService = new BaseService();
    private readonly EG_WMS_InAndOutBoundMessage inoutboundMessage = new EG_WMS_InAndOutBoundMessage();
    private readonly SqlSugarRepository<Entity.EG_WMS_InAndOutBound> _InAndOutBound = App.GetService<SqlSugarRepository<Entity.EG_WMS_InAndOutBound>>();
    private readonly SqlSugarRepository<Entity.EG_WMS_InAndOutBoundDetail> _InAndOutBoundDetail = App.GetService<SqlSugarRepository<Entity.EG_WMS_InAndOutBoundDetail>>();
    private readonly SqlSugarRepository<EG_WMS_Tem_Inventory> _TemInventory = App.GetService<SqlSugarRepository<EG_WMS_Tem_Inventory>>();
    private readonly SqlSugarRepository<EG_WMS_Tem_InventoryDetail> _TemInventoryDetail = App.GetService<SqlSugarRepository<EG_WMS_Tem_InventoryDetail>>();
    private readonly SqlSugarRepository<TaskStagingEntity> _TaskStagingEntity = App.GetService<SqlSugarRepository<TaskStagingEntity>>();
    private readonly SqlSugarRepository<EG_WMS_Storage> _Storage = App.GetService<SqlSugarRepository<EG_WMS_Storage>>();

    #endregion
    public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
    {
        // 检索暂存任务表里面有没有没有下发未完成的任务
        var taskstaging = _TaskStagingEntity.AsQueryable()
                                            .ToList();

        if (taskstaging.Count == 0)
        {
            return;
        }
        for (int i = 0; i < taskstaging.Count; i++)
        {
            // 通过物料编号再次请求库位
            EG_WMS_InAndOutBoundDetail outbounddata = _InAndOutBoundDetail.GetFirst(x => x.InAndOutBoundNum == taskstaging[i].InAndOutBoundNum);
            string requestStorage = "";
            if (taskstaging[i].InAndOutBoundNum.Contains("EGCK"))
            {
                requestStorage = baseService.AGVCacheStrategyReturnRecommendEarliestStorageOutBoundJudgeTime(outbounddata.MaterielNum);
            }
            else if (taskstaging[i].InAndOutBoundNum.Contains("EGEFCK"))
            {
                requestStorage = baseService.AGVStrategyReturnRecommendStorageOutBound(outbounddata.MaterielNum);
            }
            if (requestStorage == "没有合适的库位" || requestStorage == "等待任务完成！")
            {
                continue;
            }
            // 重新下发任务
            TaskEntity taskEntity = taskstaging[i].Adapt<TaskEntity>();
            taskEntity.TaskPath = requestStorage + taskEntity.TaskPath;
            taskEntity.Source = "暂存任务下发";
            DHMessage item = await taskService.AddOrResendTaskAsync(taskEntity);
            if (item.code == 1000)
            {
                //using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                //{
                try
                {
                    if (taskstaging[i].InAndOutBoundNum.Contains("EGCK"))
                    {
                        // 根据库位编号查询这个库位上面所存放的数据
                        var tem_InventoryDetails = _TemInventoryDetail.AsQueryable()
                            .InnerJoin<EG_WMS_Tem_Inventory>((a, b) => a.InventoryNum == b.InventoryNum)
                            .Where((a, b) => a.StorageNum == requestStorage && b.OutboundStatus == 0 && a.IsDelete == false && b.IsDelete == false)
                            .ToList();

                        //string wbnum = "";
                        int sumcount = 0;
                        for (int j = 0; j < tem_InventoryDetails.Count; j++)
                        {
                            await _TemInventory.AsUpdateable()
                                            .SetColumns(it => new EG_WMS_Tem_Inventory
                                            {
                                                OutboundStatus = 1,
                                                UpdateTime = DateTime.Now,
                                                // 出库编号
                                                OutBoundNum = taskstaging[i].InAndOutBoundNum,
                                            })
                                            .Where(x => x.InventoryNum == tem_InventoryDetails[j].InventoryNum)
                                            .ExecuteCommandAsync();

                            // 查询库存数量
                            var invCount = _TemInventory.AsQueryable()
                                         .Where(it => it.InventoryNum == tem_InventoryDetails[j].InventoryNum)
                                         .ToList();

                            // 计算总数
                            sumcount += invCount[0].ICountAll;

                        }

                        // 修改库位表中的状态为占用
                        await _Storage.AsUpdateable()
                                  .AS("EG_WMS_Storage")
                                  .SetColumns(it => new EG_WMS_Storage
                                  {
                                      // 预占用
                                      StorageOccupy = 2,
                                      TaskNo = taskstaging[i].TaskNo,
                                      UpdateTime = DateTime.Now,
                                  })
                                  .Where(x => x.StorageNum == requestStorage)
                                  .ExecuteCommandAsync();

                        // 根据库位编号查询所在区域
                        string regionnum = inoutboundMessage.GetStorageWhereRegion(requestStorage);
                        string whnum = inoutboundMessage.GetRegionWhereWHNum(regionnum);

                        // 根据得到的库位点，修改出库单据
                        await _InAndOutBound.AsUpdateable()
                                            .SetColumns(it => new EG_WMS_InAndOutBound
                                            {
                                                InAndOutBoundCount = sumcount,
                                                InAndOutBoundStatus = 5,
                                                StartPoint = requestStorage,
                                                UpdateTime = DateTime.Now,
                                            })
                                            .Where(x => x.InAndOutBoundNum == taskstaging[i].InAndOutBoundNum)
                                            .ExecuteCommandAsync();

                        await _InAndOutBoundDetail.AsUpdateable()
                                                  .SetColumns(it => new EG_WMS_InAndOutBoundDetail
                                                  {
                                                      StorageNum = requestStorage,
                                                      RegionNum = regionnum,
                                                      WHNum = whnum,
                                                      UpdateTime = DateTime.Now,
                                                  })
                                                  .Where(x => x.InAndOutBoundNum == taskstaging[i].InAndOutBoundNum)
                                                  .ExecuteCommandAsync();
                        // 完成删除暂存任务
                        _TaskStagingEntity.AsDeleteable()
                                          .Where(x => x.InAndOutBoundNum == taskstaging[i].InAndOutBoundNum)
                                          .ExecuteCommand();

                        //scope.Complete();
                    }
                    else if (taskstaging[i].InAndOutBoundNum.Contains("EGEFCK"))
                    {
                        // 根据库位编号查询所在区域
                        string regionnum = inoutboundMessage.GetStorageWhereRegion(requestStorage);
                        string whnum = inoutboundMessage.GetRegionWhereWHNum(regionnum);

                        await _InAndOutBound.AsUpdateable()
                                            .SetColumns(it => new EG_WMS_InAndOutBound
                                            {
                                                InAndOutBoundCount = 0,
                                                InAndOutBoundStatus = 5,
                                                StartPoint = requestStorage,
                                                UpdateTime = DateTime.Now,
                                            })
                                            .Where(x => x.InAndOutBoundNum == taskstaging[i].InAndOutBoundNum)
                                            .ExecuteCommandAsync();

                        await _InAndOutBoundDetail.AsUpdateable()
                                                  .SetColumns(it => new EG_WMS_InAndOutBoundDetail
                                                  {
                                                      StorageNum = requestStorage,
                                                      RegionNum = regionnum,
                                                      WHNum = whnum,
                                                      UpdateTime = DateTime.Now,
                                                  })
                                                  .Where(x => x.InAndOutBoundNum == taskstaging[i].InAndOutBoundNum)
                                                  .ExecuteCommandAsync();

                        await _Storage.AsUpdateable()
                                      .SetColumns(it => new EG_WMS_Storage
                                      {
                                          StorageOccupy = 2,
                                          TaskNo = taskEntity.TaskNo,
                                          UpdateTime = DateTime.Now,
                                      })
                                      .Where(x => x.StorageNum == requestStorage)
                                      .ExecuteCommandAsync();

                        // 完成删除暂存任务
                        _TaskStagingEntity.AsDeleteable()
                                          .Where(x => x.InAndOutBoundNum == taskstaging[i].InAndOutBoundNum)
                                          .ExecuteCommand();

                        //scope.Complete();
                    }
                }
                catch (Exception)
                {
                    //scope.Dispose();
                    return;
                }
                //}
            }
            else
            {
                return;
            }
        }
    }
}
